package com.gitee.huxing.course.conc.conc03.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc03.collection
 * @ClassName: CopyOnWriteArrayListDemo1
 * @Author: huxingmale
 * @DateTime: 2021-08-25 22:35
 */
public class CopyOnWriteArrayListDemo1 {

    private static final int THREAD_POOL_MAX_NUM = 10;

    // private List<String> mList = new ArrayList<String>();
    private List<String> mList = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws Exception{
        new CopyOnWriteArrayListDemo1().start();
    }

    private void initData(){
        for (int i = 0; i < THREAD_POOL_MAX_NUM; i++) {
            this.mList.add("...... Line " + (i + 1) + " ......");
        }
    }

    private void start() throws Exception{
        initData();
        ExecutorService service = Executors.newFixedThreadPool(THREAD_POOL_MAX_NUM);
        for (int i = 0; i < THREAD_POOL_MAX_NUM; i++) {
            service.execute(new ListReader(this.mList));
            service.execute(new ListWriter(this.mList, i));
        }
        service.shutdown();
        // 打印最后得结果
        service.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
        System.out.println(mList.toString());
    }

    private class ListReader implements Runnable {
        private List<String> mList;

        public ListReader(List<String> list) {
            this.mList = list;
        }

        @Override
        public void run() {
            if (this.mList != null) {
                for (String str : this.mList) {
                    System.out.println(Thread.currentThread().getName() + " : " + str);
                }
            }
        }
    }

    private class ListWriter implements Runnable {
        private List<String> mList;
        private int mIndex;

        public ListWriter(List<String> list, int index) {
            this.mList = list;
            this.mIndex = index;
        }

        @Override
        public void run() {
            if (this.mList != null) {
                this.mList.add("...... add " + mIndex + " ......");
            }
        }
    }
}
